package 实验第三题;

import java.io.*;
import java.util.*;

public class Question_3 {
    public static void main(String[] args) {
        File file = new File("D:/eclipse/146页3题.txt"); 
        Scanner sc = null;
        int count = 0;
        double sum = 0;

        try {
            sc = new Scanner(file);
            sc.useDelimiter("[^0123456789.]+");
            while (sc.hasNextDouble()) {
                double price = sc.nextDouble();
                count++;
                sum += price;
            }

            if (count > 0) {
                double average = sum / count;
                String Average = String.format("%.3f", average);
                System.out.println("平均价格: " + Average);

                // 追加写入平均价格到文件
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(file, true))) {
                    writer.newLine();
                    writer.write("平均价格: " + Average + "元");
                }
            } else {
                System.out.println("没有找到有效的价格数据。");
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("写入文件时出错: " + e.getMessage());
        } finally {
            if (sc != null) {
                sc.close();
            }
        }
    }
}